package suncertify.controller;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;

import suncertify.db.Data;
import suncertify.network.ServerHelper;
import suncertify.network.ServerImpl;
import suncertify.resources.App;
import suncertify.resources.ConfigurationIO;
import suncertify.ui.SearchGui;
import suncertify.ui.ServerGui;
import suncertify.ui.ServerRunningGui;

/**
 * Manages the user actions coming from the ServerGui.
 * @author Paul Wilhelm
 *
 */
public class ServerGuiController {
	
	/**
	 * Action to perform when the Save button is clicked from the server GUI.  
	 * Gets a singleton instance of the <code>ServerGui</code> object.  
	 * @throws NumberFormatException
	 * @throws FileNotFoundException
	 * @throws RemoteException
	 * @throws NotBoundException
	 * @throws IOException
	 */
	public void onSaveClick() throws NumberFormatException, FileNotFoundException, RemoteException, NotBoundException, IOException{
		ServerGui serverGui = ServerGui.getInstance();		
		SearchGui searchGui = null;							
		ConfigurationIO.writePropFile();
		if (App.isServer){								//If running in server mode, load the DB file and start the server
			Data data = Data.getInstance();
			data.loadDbFile(App.dbLocation);
			ServerRunningGui gui = ServerRunningGui.getInstance();
			ServerImpl server = new ServerImpl(App.port);
			server.startServer();
			gui.buildAndShowGui();
			serverGui.closeGui();
			return;
		}
		else if (App.isNetworked){						//If running in networked-client mode, set the remote DB file and set the SearchGui
			ServerHelper.setRemoteDatabase(App.host, App.port);
			searchGui = SearchGui.getInstance();	
		}
		else {											//If running in stand-alone mode, locad the DB file and set the SearchGui.
			Data data = Data.getInstance();
			data.loadDbFile(App.dbLocation);
			searchGui = SearchGui.getInstance();
		}
		serverGui.closeGui();
		if (searchGui != null){							//If the SearchGui is no longer null, build and show the gui.
			searchGui.buildAndShowGUI();
		}
	}
}
